
#include "XBeeRequest.h"
#include "XBeeSerial.h"

XBeeRequest::XBeeRequest(char apiID, char frameID, const char* data, int dataLength) {
    this->apiID = apiID;
    this->frameID = frameID;
    this->msgData = new char[dataLength];
    for(int i=0; i < dataLength; i++)
        msgData[i] = data[i];
    
    this->msgDataLength = dataLength;
}

XBeeRequest::~XBeeRequest() {

}

int XBeeRequest::getLength()
{
    int len = (use64BitAddress ? 8 : 0) +
        (use16BitAddress ? 2 : 0) +
        msgDataLength +
        2; // For apiID, msgID

    return len;
}
        
char* XBeeRequest::getFullMessage()
{
    char* ret = new char[getLength()];

    ret[0] = apiID;
    ret[1] = frameID;

    int curByte = 2;

    if (use64BitAddress)
    {
        char* addr = int64ToBytes(address64);

        addArrayToArray(ret, addr, curByte, 8);
        curByte += 8;
        delete addr;
    }

    if (use16BitAddress)
    {
        char* addr = int16ToBytes(address16);

        addArrayToArray(ret, addr, curByte, 2);
        curByte += 2;
        delete addr;
    }

    addArrayToArray(ret, msgData, curByte, msgDataLength);

    return ret;
}
        
char XBeeRequest::calcChecksum() {
    return (char)(0xFF - (getMessageSum() % 0xFF));
}

char* XBeeRequest::buildRequest() 
{
    char* fullMsg = getFullMessage();
    int fullMsgLen = getLength();
    
    int reqLen = fullMsgLen+4;
    char* request = new char[reqLen];

    request[0] = API_PACKET_START;

    char* msgLen = int16ToBytes(fullMsgLen);

    request[1] = msgLen[0];
    request[2] = msgLen[1];

    delete msgLen;
    
    for(int i = 0; i < fullMsgLen; i++)
        request[i+3] = fullMsg[i];

    request[reqLen-1] = calcChecksum();

    return request;
}

